<template>
  <div class="visit_time" v-loading="loading">
    <div class="top">
      <affix :label="$t('call.queryTerm')"></affix>
      <div class="search">
        <template>
          <date-time type="other" :query="query"></date-time>
        </template>
        <div class="source">
          <span class = "condi">{{$t('report.imReportFrom')}}</span>
          <el-select size="mini"
                     v-model.trim="fromUrl"
                     multiple
                     filterable
                     :placeholder="$t('report.imReportFrom')">
              <el-option v-for="item in fromUrlList"
                        :key="item._id"
                        :label="item.urlTitle"
                        :value="item._id"></el-option></el-select></div>
        <div class="source">
          <el-row>
            <el-col class="condi">
              <span>{{$t('report.imReportArea')}}</span>
            </el-col>
            <el-col :span="10" class="provin">
              <el-select size="mini"
                     v-model.trim="area"
                     multiple
                     filterable
                     :placeholder="$t('report.pleasePro')">
                <el-option v-for="(item, index) in province"
                           :label="item"
                           :value="item"
                           :key="index"></el-option></el-select>
            </el-col>
          </el-row>
        </div>
        <el-button type="primary" class="primary_btn fr find" @click.stop="search">{{$t('public.search2')}}</el-button>
        <div class="clear"></div>
      </div>
      <affix :label="title"></affix>
      <div class="export">
        <el-button type="primary" class="primary_btn fr turnCha" @click.stop="changeHighChartsType">{{chart}}</el-button>
        <el-button type="primary" class="primary_btn fr" @click.stop="exportXls">{{$t('report.exportXls')}}</el-button>
        <el-button type="primary" class="primary_btn fr pdf" @click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
      </div>
    </div>
    <div :id="id">
      <el-row class="ichars">
        <highcharts :options="highchartsOptions"></highcharts>
        <div class="notes">
            <span class="light">注: <span></span>点亮，图中显示对应数据；</span>
            <span class="dark"><span></span>变暗，图中隐藏对应数据</span>
          </div>
      </el-row>
      <div class="tab">
        <!-- <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                {{$t('report.toggleInstructe')}}
              </template>
              <div>
                IP数: 访问您网站的独立IP数，相同IP多次访问网站时，只被记录1次<br>
                PV数: 访客每次打开网站页面被记录1次。访客多次打开同一页面，访问量值累计多次。此指标衡量网站访问量情况<br>
                UV数: 访问您网站的访客人数，同一访客多次访问您网站只计算1个访客。<br>
                新访客数: 首次访问网站的访客记为一个新访客。<br>
                人均浏览次数: PV（页面浏览次数）/UV<br>
                点击咨询人数: 点击按钮，进行在线咨询的人数，排重<br>
                离开人数: 未和座席产生会话而离开的人数，排重<br>
                平均访问时长: 平均每次访问在网站上的停留时长，=所有访客浏览网站的总时长/PV<br>
                平均访问页数: 平均每次访问所浏览的网站页数，=所有访客访问页面的总数量/UV
              </div>
            </el-collapse-item>
          </el-collapse>
        </div> -->
        <!-- <report-table :data="tableData" :sum="totalData" :config="headOptions.Config"></report-table> -->
        <div class="table">
          <el-table :data="tableData"
                    stripe
                    size="mini"
                    style="width: 100%">
            <el-table-column prop="guest"
                             label="访客类型"></el-table-column>
            <el-table-column prop="onlyGuest"
                             label="独立访客数"></el-table-column>
            <el-table-column prop="Proportion"
                             label="比例"></el-table-column></el-table>
        </div>
      </div>
    </div>
    <el-dialog modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import affix from '../../../../ui-modules/affix/Affix.vue'
  // import AreaLinkage from '@/components/ui-modules/area-linkage/AreaLinkage.vue'
  import dateTime from '../../base/datetime.vue'
  // import reportTable from '../../base/reportTable.vue'
  import { deepClone } from '@/utils/m7Utils.js'
  import { exportReportPdf, checkTime, searchTime, colorConfigArr } from '@/utils/reportUtils.js'
  export default {
    name: 'visit_time',
    data () {
      return {
        fromUrl: [],
        area: [],
        province: ['上海', '浙江', '西沙群岛', '澳门', '台湾', '甘肃', '香港', '宁夏', '陕西', '安徽', '湖北', '广东', '福建', '北京', '河北', '山东', '天津', '江苏', '海南', '青海', '吉林', '西藏', '新疆', '河南', '内蒙古', '黑龙江', '云南', '广西', '辽宁', '四川', '重庆', '贵州', '湖南', '山西', '江西'],
        chart: '折线图',
        selectedAgentList: [],
        fromUrlList: [],
        id: 'im_loyalty_report_timeLength',
        title: '访问时长',
        loading: false,
        timeType: 'day',
        query: {
        },
        // tableData: [{
        //   guest: '新访客',
        //   onlyGuest: '王小虎',
        //   Proportion: '上海市普陀区金沙江路 1518 弄'
        // }, {
        //   guest: '回访者',
        //   onlyGuest: '王小虎',
        //   Proportion: '上海市普陀区金沙江路 1518 弄'
        // }],
        dialogVisible: false,
        serverData: [],
        headOptions: { Config: [], data: [] },
        highchartsDefaultOptions: {
          chart: {
            type: 'column',
            animation: false
          },
          colors: colorConfigArr,
          xAxis: {
            type: 'category'
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: { text: '' },
            showEmpty: false
          },
          title: {
            text: '访问时长'
          },
          legend: { enabled: false },
          tooltip: {
            headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
            pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y}</b><br/>'
          },
          credits: { enabled: false },
          series: []
        }
      }
    },
    components: {
      affix,
      dateTime
      // reportTable
      // ,
      // AreaLinkage
    },
    computed: {
      tableData () {
        if (!this.serverData || this.serverData.length === 0) {
          return []
        }
        let datas = deepClone(this.serverData)
        let data = []
        let allNum = 0
        for (let i = 0; i < datas.length; i++) {
          allNum += datas[i].count
        }
        datas.map((item, index) => {
          if (index < 2) {
            if (index === 0) {
              data.push({
                guest: '0-8秒',
                onlyGuest: item.count,
                Proportion: allNum > 0 ? Math.round(item.count / allNum * 100) + '%' : '0%'
              })
            }
            if (index === 1) {
              data.push({
                guest: '8-60秒',
                onlyGuest: item.count,
                Proportion: allNum > 0 ? Math.round(item.count / allNum * 100) + '%' : '0%'
              })
            }
          } else {
            data.push({
              guest: (index !== datas.length - 1) ? `${(index - 1) * 60}-${index * 60}秒` : '1800秒以上',
              onlyGuest: item.count,
              Proportion: allNum > 0 ? Math.round(item.count / allNum * 100) + '%' : '0%'
            })
          }
        })
        return data
      },
      highchartsOptions () {
        let options = deepClone(this.highchartsDefaultOptions)
        if (!this.serverData || this.serverData.length === 0) {
          return options
        }

        let datas = this.serverData
        let seriesArray = [{
          name: '独立访客数',
          data: []
        }]

        for (let i = 0; i < datas.length; i++) {
          if (i < 2) {
            if (i === 0) {
              seriesArray[0].data.push({
                name: '0-8秒',
                y: datas[i].count
              })
            }
            if (i === 1) {
              seriesArray[0].data.push({
                name: '8-60秒',
                y: datas[i].count
              })
            }
          } else {
            seriesArray[0].data.push({
              name: (i !== datas.length - 1) ? `${(i - 1) * 60}-${i * 60}秒` : '1800秒以上',
              y: datas[i].count
            })
          }
        }

        options.series = seriesArray
        return options
      }
    },
    methods: {
      search () {
        let query = deepClone(this.query)
        if (query.timeType === 'other') {
          let message = checkTime(query.StartTime, query.EndTime, false, true) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        let data = {
          reportType: this.id,
          account: this.$store.state.session.user.account,
          query: {
            reportType: this.id,
            area: this.area,
            fromUrl: this.fromUrl

          }
        }
        data.query = Object.assign({}, data.query, query)
        this.$store.dispatch('queryLoyaltyReport', data).then((res) => {
          if (res.success) {
            this.fromUrlList = res.fromUrlList
            this.serverData = deepClone(res.data)
          }
        })
      },
      changeHighChartsType () {
        if (this.chart === '折线图') {
          this.chart = '柱状图'
          this.highchartsDefaultOptions.chart.type = 'line'
        } else {
          this.chart = '折线图'
          this.highchartsDefaultOptions.chart.type = 'column'
        }
      },
      exportXls () {
        let data = {
          Method: 'exportImLoyaltyReport',
          Query: {
            reportType: this.id,
            user: this.$store.state.session.user._id,
            area: this.area,
            fromUrl: this.fromUrl
          }
        }
        let query = deepClone(this.query)
        if (query.timeType === 'other') {
          let message = checkTime(query.StartTime, query.EndTime, false, true) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        data.Query = Object.assign({}, data.Query, query)
        this.$store.dispatch('exportImSessionTimeReport', data)
      },
      exportPdf () {
        this.dialogVisible = true
      },
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.webchat') + '访问时长' + searchTime(this.query), id: this.id})
      }
    },
    beforeMount () {
      this.$nextTick(() => {
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .visit_time
    .top
      padding 28px 16px 0
    .provin
      width 600px
    .source
      .el-select
        width 600px
    .el-button
      margin 0 0 0 10px
    .source
      padding-left 18px
      margin 20px 0
      .condi
        width 58px
        display inline-block
        line-height 30px
    .tab
      .table
        padding-bottom 20px
      .deploy
        .tip
          margin-left 0px
</style>
